package qgs.ddjdispachingsystem.ddj.wcs.controller;

import com.ioserver.bean.Union_DataType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.bind.annotation.*;
import qgs.ddjdispachingsystem.ddj.ioserver.IOServerService;
import qgs.ddjdispachingsystem.ddj.wcs.entity.CargoArg;
import qgs.ddjdispachingsystem.ddj.wcs.entity.DDJJobEntity;
import qgs.ddjdispachingsystem.ddj.wcs.entity.WeightingEntity;
import qgs.ddjdispachingsystem.ddj.wcs.entity.WeightingPLCEntity;
import qgs.ddjdispachingsystem.ddj.wcs.enums.IOServerEnum;

import qgs.ddjdispachingsystem.ddj.wcs.service.DDJService;
import qgs.ddjdispachingsystem.ddj.wcs.service.WeighingPLCService;

import java.io.IOException;
import java.util.List;


/**
 * @Author: 蔡翔
 * @Date: 2019/10/12 15:15
 * @Version 1.0
 */
@RestController
    @RequestMapping("/wmcTest")
public class WmcController {

    private static final Logger logger = LoggerFactory.getLogger(WmcController.class);

    IOServerService ioServerService = new IOServerService();

    @Autowired
    DDJService ddjService;

    @Autowired
    WeighingPLCService weighingPLCService;



    // 测试（数据类型） 和plc通讯
    /**
     * 测试real 类型（get / set）
     **/
    @PostMapping("/testReal")
    public R testReal() throws Exception {
        Integer integer = ioServerService.setTagValue(IOServerEnum.Take_Position.getCollectionPointName(), "55", 2);
        Thread.sleep(1000);
        Union_DataType.ByValue valueByName = ioServerService.getValueByName(IOServerEnum.Take_Position.getCollectionPointName());
        return R.ok().put("Take_Position",valueByName);
    }

    /**
     * 测试real 类型（get / set）
     **/
    @PostMapping("/noRR")
    public R noRR() throws Exception {
        return R.ok().put("OK",123);
    }

    /**
     * 测试boolen 类型（get / set）
     **/
    @PostMapping("/testBoolen")
    public R testBoolen() throws Exception {
        Integer integer = ioServerService.setTagValue(IOServerEnum.L_Start.getCollectionPointName(), "1", 4);
        Thread.sleep(1000);
        Union_DataType.ByValue valueByName = ioServerService.getValueByName(IOServerEnum.L_Start.getCollectionPointName());
        return R.ok().put("L_Start",valueByName);
    }
    /**
     * 测试Byte 类型（get / set）
     **/
    @PostMapping("/testByte")
    public R testByte() throws Exception {
        Integer integer = ioServerService.setTagValue(IOServerEnum.Device_Status.getCollectionPointName(), "88", 5);
        Thread.sleep(1000);
        Union_DataType.ByValue valueByName = ioServerService.getValueByName(IOServerEnum.Device_Status.getCollectionPointName());
        return R.ok().put("Device_Status",valueByName);
    }

    /**
     * 测试接口超时时间
     **/
    @PostMapping("/testInterfaceOutTime")
    public R testInterfaceOutTime() throws Exception {
        Integer i= 1;
        while (true){
            if(i!=1){
                break;
            }
            Thread.sleep(10000);
        }
        return R.ok();
    }

    /**
     * caixiang
     *
     * 输入值：
     *      targetPosition  代表 起点
     *      takePosition    代表 终点
     *      type            代表 1《==》入库；；2 《==》 出库
     *      position        代表 某个口子
     *
     * 返回值:
     *      -1 代表 IOServer 写入异常
     *      -2 代表 堆垛机在执行任务途中 出现故障。
     *      1 代表 堆垛机执行成功
     *      2 代表 重置任务失败。
     *      3 代表 分发任务失败
     *
     *  给堆垛机下发任务并且监听
     *
     * status : work
     **/
    @PostMapping("/sendTaskAndListening")
    public R sendTaskAndListening(@RequestBody DDJJobEntity ddjJobEntity) throws Exception {
        System.out.println(ddjService.getClass().toString()+"  "+ddjService.hashCode());
        Integer integer = ddjService.sendTaskAndListening(ddjJobEntity);
        return R.ok().put("result",integer);
    }

    @PostMapping("/testLoggerErr")
    public R testLoggerErr() throws Exception {
        logger.error("测试错误");
        return R.ok();
    }

    @PostMapping("/shutdownCurrentTask")
    public R shutdownCurrentTask() throws Exception {
        Integer integer = ddjService.stopCurrentTask();
        return R.ok().put("result",integer);
    }

    /**
     * 给称重plc 下达称重 指令（第一步）
     * Arg
     *          type  1 代表入库 ；； 2 代表出库
     * return
     *          -1  代表 IOServer 写入异常
     *          -2  代表 IOServer 写入失败
     *          0   代表写入 成功
     *
     * status ：work
     **/
    @PostMapping("/warehousingBegin")
    public R warehousingBegin(@RequestBody WeightingEntity weightingEntity) throws Exception {
        Integer integer = weighingPLCService.warehousingBegin(weightingEntity.getType(),weightingEntity.getPosition());
        return R.ok().put("result",integer);
    }

    /**
     *  给称重plc 发送 指令后 去 取值（第二步）
     * */
    @PostMapping("/getCargoAllMessage")
    public R getCargoAllMessage(@RequestBody CargoArg cargoArg) throws Exception {
        WeightingPLCEntity cargoAllMessage = weighingPLCService.getCargoAllMessage(Integer.parseInt(cargoArg.getCargoWeight().toString()),Integer.parseInt(cargoArg.getCargoHeight().toString()));
        return R.ok().put("result",cargoAllMessage);
    }





    //测试Short 类型
    @PostMapping("/setCargoArg")
    public R setCargoArg(@RequestBody CargoArg cargoArg) throws Exception {
        return R.ok().put("result",ddjService.modifyCargoArg(cargoArg));
    }

    //测试Byte 类型
    @PostMapping("/setDeviceStatus")
    public R setDeviceStatus(@RequestBody CargoArg cargoArg) throws Exception {
        return R.ok().put("result",ddjService.modifyDeviceStatus(cargoArg));
    }

    //测试Boolen 类型
    @PostMapping("/setLStart")
    public R setLStart(@RequestBody CargoArg cargoArg) throws Exception {
        return R.ok().put("result",ddjService.modifyDeviceLstart(cargoArg));
    }

    //测试Word 类型  Word 统一用Short 类型，Short 16位的。Word 是两个字节（16位的）
    @PostMapping("/setFirstHeight")
    public R setAndGetFirstHeight(@RequestBody CargoArg cargoArg) throws Exception {
        ddjService.modifyCargoFirstHeight(cargoArg);
        Thread.sleep(1000);
        Union_DataType.ByValue frist_height = ioServerService.getValueByName("Frist_Height");
        return R.ok().put("result",frist_height);
    }

    //测试Word 类型  Word 统一用Short 类型，Short 16位的。Word 是两个字节（16位的）
    @PostMapping("/pushSensorAlarmMessage")
    public R pushSensorAlarmMessage(@RequestBody CargoArg cargoArg) throws Exception {
        int i = Integer.parseInt(cargoArg.getCargoWeight().toString());
        List<Character> characters = weighingPLCService.getSensorAlarmMessage(i);
        return R.ok().put("result",characters);
    }

}
